<template>
  <div class="header-bar">
    <img
      style="height: 100%"
      src="../../assets/img/logo.png"
      alt=""
      @click="toHome"
      class="pointer"
    />
    <div class="btn-history">
      <i class="el-icon-arrow-left pointer" @click="goTo(-1)"></i>
      <i class="el-icon-arrow-right pointer" @click="goTo(1)"></i>
    </div>
    <div class="search-input">
      <el-input
        placeholder="搜索"
        v-model="keywords"
        ref="inputRef"
        clearable
        prefix-icon="el-icon-search"
        @change="toSearch"
        @focus="getHotSearchList"
        @blur="showInfoTip = false"
        @input="handleInput"
      >
      </el-input>
      <transition name="el-fade-in">
        <!-- 热搜及其搜索建议 -->
        <div class="search-info-tip" v-show="showInfoTip">
          <div v-show="keywords === ''">
            <div v-show="historySearchList.length !== 0">
              <div class="hot-title font-14">
                <span>搜索历史</span>
                <button class="no-btn" @click="clearHis">
                  <i class="el-icon-delete"></i>
                </button>
              </div>
              <div class="his-wrap">
                <button
                  class="btn btn-white his-item font-12"
                  v-for="val in historySearchList"
                  :key="val"
                  @click="clickHot(val)"
                >
                  {{ val }}
                </button>
              </div>
            </div>
            <!-- 热门搜索 -->
            <div class="hot-search">
              <div class="hot-title font-14">热门搜索</div>
              <div
                class="hot-item pointer"
                :class="{'top-item':index < 3}"
                v-for="(item , index) in hotSearchList"
                :key="index"
                @click="clickHot(item.searchWord)"
              >
              <div class="item-index">{{index + 1}}</div>
              <div>
                <div>
                  <span class="font-12 item-key">{{item.searchWord}}</span>
                  <span style="color: #c2c1c1" class="font-12 mleft-10">{{item.score}}</span>
                </div>
                <div>
                  <span style="color:#999999" class="font-12">{{item.content}}</span>
                </div>
              </div>
            </div>
            </div>
          </div>
          <div v-show="keywords !== ''">
            <div>
              <div class="search-btn-warp">
                <button class="no-btn">
                  搜“{{keywords}}”相关的内容<i class="el-icon-arrow-right"></i>
                </button>
              </div>
              <SuggestList v-if="showMusic">
                <template #title>
                  <i class="iconfont icon-yinle font-16"></i>
                  <span class="mleft-10">单曲</span>
                </template>
                <template #item>
                  <div 
                    v-for="song in suggestInfo.songs"
                    :key="song.id"
                    class="item pointer text-hidden"
                    @click="playMusic(song.id)"
                  >
                  {{song.name}} -{{song.artists[0].name}}
                  </div>
                </template>
              </SuggestList>
              <SuggestList v-if="showAlbum">
                <template #title>
                  <i class="iconfont icon-zhuanji font-16"></i
                  ><span class="mleft-10">专辑</span>
                </template>
                <template #item>
                  <div
                    v-for="al in suggestInfo.albums"
                    :key="al.id"
                    class="item pointer text-hidden"
                    @click="toAlbumDetail(al.id)"
                  >
                    {{ al.name }} - {{ al.artist.name }}
                  </div>
                </template>
              </SuggestList>
              <SuggestList v-if="showArtist">
                <template #title
                  ><i class="el-icon-user font-16"></i
                  ><span class="mleft-10">歌手</span>
                </template>
                <template #item>
                  <div
                    v-for="ar in suggestInfo.artists"
                    :key="ar.id"
                    class="item pointer text-hidden"
                    @click="toArtistDetail(ar.id)"
                  >
                    {{ ar.name }}
                  </div>
                </template>
              </SuggestList>
              <SuggestList v-if="showPlaylist">
                <template #title>
                  <i class="iconfont icon-gedan font-16"></i
                  ><span class="mleft-10">歌单</span>
                </template>
                <template #item>
                  <div
                    v-for="p in suggestInfo.playlists"
                    :key="p.id"
                    class="item pointer text-hidden"
                    @click="toPlayListDetail(p.id)"
                  >
                    {{ p.name }}
                  </div>
                </template>
              </SuggestList>
            </div>
          </div>
        </div>
      </transition>
    </div>
    <div class="avatar-wrap mleft-10 pointer" @click="loginView">
      <el-avatar
        :size="30"
        icon="el-icon-user-solid"
        :src="avatarUrl"
      ></el-avatar>
    </div>
    <div class="login-info mleft-10 font-12 "
          :class="{pointer:isLogin}"   
          @click="doLogout"   
    >{{name}}</div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {getHotSearch, getSuggestSearch} from "../../api/request"
import SuggestList from "../../components/list/SuggestList.vue"
export default {
  components:{SuggestList},
  data() {
    return {
      keywords: "",
      //搜索历史
      historySearchList: [],
      showInfoTip: false,
      hotSearchList:[],//热门搜索
      suggestInfo:{},//建议搜索
    };
  },
  computed:{
    showMusic(){
      return Object.hasOwnProperty.call(this.suggestInfo, "songs");
    },
    showAlbum() {
      return Object.hasOwnProperty.call(this.suggestInfo, "albums");
    },
    showArtist() {
      return Object.hasOwnProperty.call(this.suggestInfo, "artists");
    },
    showPlaylist() {
      return Object.hasOwnProperty.call(this.suggestInfo, "playlists");
    },
    ...mapState(["isLogin","account","profile"]),
    name(){
      return this.isLogin ? this.profile.nickname : "未登录";
    },
    avatarUrl(){
      return this.isLogin ? this.profile.avatarUrl : ""
    }
  },
  created() {
    this.getHistory();
  },
  methods: {
    toHome() {
      if (this.$route.path !== "/discover/personalrecom")
        this.$router.push("/discover/personalrecom");
    },
    goTo(step) {
      this.$router.go(step);
    },
    toSearch() {
      if (this.keywords == "") return;
      this.$refs.inputRef.blur();
      if (this.$route.path != "/search?keywords=" + this.keywords) {
        this.$router.push(
          `/search?keywords=${encodeURIComponent(
            encodeURIComponent(this.keywords)
          )}`
        );
      }
      this.setHistory(this.keywords);
    },
    // 获取搜索历史
    getHistory() {
      if (!window.localStorage.getItem("search")) return;
      this.historySearchList =
        JSON.parse(window.localStorage.getItem("search")) instanceof Array
          ? JSON.parse(window.localStorage.getItem("search"))
          : [];
    },
    // 保存历史搜索
    setHistory(val) {
      if (val) {
        if (this.historySearchList.findIndex((item) => item == val) !== -1)
          return;
        this.historySearchList.unshift(val);
        this.historySearchList = this.historySearchList.slice(0, 5);
        window.localStorage.setItem(
          "search",
          JSON.stringify(this.historySearchList)
        );
      }
    },
    clearHis() {
      this.$confirm("确认清空历史记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.localStorage.removeItem("search");
        this.historySearchList = [];
      });
    },
    clickHot(val){
      if(val !== ""){
        this.keywords =  val;
        this.toSearch();
      }
    },
    //获取热门搜索列表
    async getHotSearchList(){
      this.showInfoTip = true;
      if(this.keywords !== ""){
        this.getSuggest(this.keywords);
      }
      if(this.hotSearchList.length !== 0) return;
      const {data:res} = await getHotSearch();
      this.hotSearchList = res.data;
    },
    // input防抖事件
    handleInput(val){
      if(this.timer){
        window.clearTimeout(this.timer);
      }
      this.timer = window.setTimeout(() => {
        this.getSuggest(val)
      },500)
    },
    //音乐搜索建议
    async getSuggest(val){
      if(val == "") return;
      const {data:res} = await getSuggestSearch({keywords : val});
      if(res.code !== 200) return;
      if(Object.keys(res.result).length !== 0) this.suggestInfo = res.result;
    },
    playMusic(id){
      console.log("播放音乐",id);
    },
    toAlbumDetail(id){
      this.$router.push("/albumdetail/" + id);
    },
    toArtistDetail(id){
      this.$router.push("/artistdetail/" + id);
    },
    toPlayListDetail(id){
      if(typeof id === 'number'){
        this.$router.push('/playlistdetail/' + id);
      }
    },
    // 登录
    loginView(){
      if(!this.isLogin) this.$router.push('/login');
      else {
        if(this.$route.path === '/userdetail/' + this.account.id) return;
        this.$router.push("/userdetail/" + this.account.id);
      }
    },
    doLogout(){
      this.$store.dispatch('logout');
    }
  },
};
</script>

<style lang="less" scoped>
.header-bar {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  background-color: #ff2727;
}
.btn-history {
  margin-left: 100px;
  color: #fff;
  .el-icon-arrow-left {
    margin-right: 20px;
  }
}
.search-input {
  margin-left: 20px;
  position: relative;
  .search-info-tip {
    position: absolute;
    top: 40px;
    left: 0;
    width: 340px;
    min-height: 340px;
    max-height: 420px;
    transition: all 0.5s;
    overflow-y: auto;
    border-radius: 8px;
    box-shadow: 0 1px 4px #dddddd;
    background-color: #fff;
    z-index: 100;
    color: #000;
  }
}
.his-wrap {
  display: flex;
  padding: 0 18px;
  flex-wrap: wrap;
  .his-item {
    margin: 0 10px 10px 0;
    height: 26px;
  }
}
.hot-title {
  color: #666666;
  margin: 10px auto 10px 10px;
}
.hot-search{
    margin-top: 20px;
    .hot-item{
      height: 50px;
      display: flex;
      align-items: center;
      &:hover{
        background-color: #f2f2f2;
      }
      .item-index{
        color: #c2c2c2;
        width: 40px;
        text-align: center;
      }
  }

  .top-item{
    .item-index{
      color: #e13e3e;
    }
    .item-key{
      font-weight: bold;
    }
  }
}
.search-btn-warp{
  height: 30px;
  line-height: 30px;
}
.login-info{
  white-space: nowrap;
}
</style>